#!/usr/bin/env bash
# Copyright (C) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE in project root for information.

. "$(dirname "${BASH_SOURCE[0]}")/../../runme"
@ "shared.sh"

PRDIR="$BASEDIR/.build-pr"
_md "$PRDIR"

# make it possible to use the main version of these files later too
_ cp -a "$TOOLSDIR/build-pr" "$PRDIR/build-pr"

if [[ "$BUILDPR" = "" ]]; then exit 0; fi

printf "========================================\n"
if [[ "$BUILDPR" = */*/* ]]; then
  echo "##[section] Branch Build for $BUILDPR"
else
  echo "##[section] PR Build for #$BUILDPR"
fi
get_pr_info
repourl="https://github.com/$REPO"
printf '  repo: %s\n  ref: %s\n  sha1: %s\n' "$REPO" "$REF" "$SHA1"
printf "========================================\n"

git checkout -f "master" > /dev/null 2>&1
oldbr="$(git for-each-ref --format="%(refname:short)" "refs/heads/pr-*")"
if [[ -n "$oldbr" ]]; then git branch -D "$oldbr"; fi

text="A build has started.  (${SHA1:0:8})"
post_status "pending" "$text"
post_comment "$text"

_get_T
bname="pr-$BUILDPR"; bname="${bname//\//-}"
git fetch "https://$T@github.com/$REPO" "$REF:refs/heads/$bname"
git checkout "$bname"
git reset --hard "$SHA1"

# useful info in build
{ if [[ "$BUILDPR" = */*/* ]]; then txt="Github Branch $BUILDPR"
  else txt="Github PR #$BUILDPR"; fi
  printf '### This is a build for %s, changes:\n\n' "$(md_link "$txt" "$GURL")"
  git log --format="* [[%h]($repourl/commit/%H)] [%aN](mailto:%aE) %s" \
      "origin/master..$SHA1"
  printf '\n---\n'
  } > "$PRDIR/PR-Build.md"

# variable overrides
prvar() { printf '%s=%q\n' "$1" "$2" >> "$TOOLSDIR/local-config.sh"; }
prvar BUILD_SOURCEVERSION        "$SHA1"
prvar BUILD_REPOSITORY_NAME      "$REPO"
prvar BUILD_REPOSITORY_ID        "$repourl"
prvar BUILD_REPOSITORY_URI       "$repourl"
prvar BUILD_SOURCEBRANCH         "refs/heads/$REF"
prvar BUILD_SOURCEBRANCHNAME     "$(basename "$REF")"
prvar BUILD_SOURCEVERSIONAUTHOR  "$(git log -1 --format="%aN <%aE>")"
prvar BUILD_SOURCEVERSIONMESSAGE "$(git log -1 --format="%s")"
prvar BUILD_INFO_EXTRA_MARKDOWN  "$PRDIR/PR-Build.md"
